'use strict';
var fs=require('fs');

const Controller = require('egg').Controller;
const cheerio = require('cheerio')
class DemoController extends Controller {
  async index() {
	var ctx = this.ctx;
	fs.mkdir('txt',function(error){
		if(error){
			return false;
		}
		console.log('创建目录成功');
	})
	let page = 1;
	let PhotoJson = "";
	GetPageDatile();
	let m = 0;
	async function GetPageDatile(){
		const PhotoH = await ctx.service.spider.getPhoto(page);
		const $ = cheerio.load(PhotoH.data);
		if($(".smallCards a.posr").length===0){
			console.info("搜索完毕");
			return;
		}
		let len = $(".smallCards a.posr").length;
		console.info($(".smallCards a.posr .cardImage").length,page);
		var interval = setInterval(async() => {
			let item = $(".smallCards a.posr").eq(m);
			let _avatar_img = $("._avatar--user").eq(m);
			let _avatar_name = $(".username").eq(m);
			if(item.find(".cardImage").length>0){
				let imgStr = "",plain = "",_id="",title="";
				let jsonPart = "";
				let href = item.attr("href");
				const PhotoD = await ctx.service.spider.getPhotoDetail(href);
				const $d = cheerio.load(PhotoD.data);
				jsonPart = $d("script").eq(5).html().replace(/[\r\n\s]/g,"").match(/JSON.parse\(\"(\S*)\"\)\;/)[1].replace(/\\"/g,'"');
				try{
					jsonPart = JSON.parse(jsonPart);
					jsonPart.detail.post_data.multi.forEach((itemL,j) => {
						imgStr += itemL.path;
						imgStr = j === (jsonPart.detail.post_data.multi.length-1)?imgStr:(imgStr+",");
					});
					
					plain = jsonPart.detail.post_data.plain;
					_id = jsonPart.detail.post_data.item_id;
					title = jsonPart.detail.post_data.title;
					console.info(m,page,_avatar_name.html(),plain);
					PhotoJson +='{_pid:"'+_id+'",title:"'+title+'",imgStr:"'+imgStr+'",plain:"'+plain+'",imageF:"'+item.find("img").eq(0).attr("src")
					+'",atvatarImg:"'+_avatar_img.find("img").attr("src")+'",atvatarName:"'+_avatar_name.html()+'"}';
				}catch(e){
					console.info("error",m);
				}
			}
			fs.writeFile('txt/jsonPhoto.json',PhotoJson,'utf8',function(error){
				if(error){
					return false;
				}
			});
			if(m===len||$(".smallCards a.posr .cardImage").length===0){
				page++;
				m=0;
				clearInterval(interval);
				GetPageDatile();
			}else{
				m++;
			}
		},1200)
	};
	let ob = {ary:[]};
	await ctx.render('photo.tpl', ob);
  }
}

module.exports = DemoController;
